package com.tarena.test.lbs.es;

import com.alibaba.fastjson2.JSON;
import com.tarena.test.lbs.es.pojo.Student;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ESDocTestRun {
    private RestHighLevelClient client;

    @Before
    public void initClient(){
        HttpHost host = new HttpHost("localhost", 9200, "http");
        RestClientBuilder builder = RestClient.builder(host);
        client = new RestHighLevelClient(builder);
    }

    //创建文档
    @Test
    public void createDoc() throws IOException{
        //1.创建文档对应的请求
        IndexRequest request = new IndexRequest();
        //2.指定索引名称和索引数据
        request.index("test03");
        request.source(
                "{\"name\":\"王翠花\",\"gender\":\"女\",\"birthday\":\"2000-06-19\",\"location\":\"39.9042,116.4074\",\"student_no\":\"20210001\"}",
                XContentType.JSON);
        //设置文档Id
        request.id("20210001");
        //执行登录
        client.index(request, RequestOptions.DEFAULT);
    }

    //利用文档Id 湖区文档
    @Test
    public void getDoc() throws IOException{
        //1.构造一个查询请求
        GetRequest request = new GetRequest();
        //2.指定文档Id
        request.index("test03");
        request.id("20210001");
        //读取索引文档的数据,
        GetResponse documentResponse = client.get(request, RequestOptions.DEFAULT);
        //2.1从相应中获取一些源文件
        String index = documentResponse.getIndex();
        //2.2获取不同格式的文档数据
        Map<String, Object> sourceAsMap = documentResponse.getSourceAsMap();
        sourceAsMap.forEach((k,v)->{
            System.out.println("k="+k+";v="+v);
        });
        String sourceAsString = documentResponse.getSourceAsString();
        System.out.println(sourceAsString);
        //3.使用类型封装JSON变成一个对象
        Student student1 = JSON.parseObject(sourceAsString, Student.class);
        Student student2 = JSON.parseObject(JSON.toJSONString(sourceAsMap), Student.class);
        System.out.println(student1);
        System.out.println(student2);
    }

    //更新部分数据
    @Test
    public void updateDoc() throws IOException{
        UpdateRequest request = new UpdateRequest("test03","20210001");
        //2.携带更新的内容
        Map<String,Object> updateFileds=new HashMap<>();
        updateFileds.put("gender","男");
        updateFileds.put("name","刘翠花");
        request.doc(updateFileds);
        //3.执行请求
        client.update(request,RequestOptions.DEFAULT);
    }
}
